package com.qf.qfarticle.listeners;

import com.qf.qfarticle.service.ApArticleService;
import com.qf.qfleadnewsfeignapi.wemedia.WmNewsApi;
import com.qf.qfleadnewsmodel.commons.consts.KafkaConst;
import com.qf.qfleadnewsmodel.commons.consts.RedisConst;
import com.qf.qfleadnewsmodel.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class NewsPublishListener {

    @Autowired
    private WmNewsApi wmNewsApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ApArticleService apArticleService;

    @KafkaListener(topics = KafkaConst.NEWS_PUBLISH_TOPIC)
    public void newsPub(String newsId, Acknowledgment acknowledgment) {
        log.info("收到文章发布消息，消息id为：{}",newsId);

        String key = RedisConst.NEWS_PUBLISH_MD_PREFIX + newsId;
        try {
            //根据newsId，查询wmnews信息（远程查询）
            WmNews wmNews = wmNewsApi.findById(Integer.parseInt(newsId));
            log.info("收到文章发布消息，查询到的wmnews信息为：{}",wmNews);

            if (wmNews != null) {
                //todo： 幂等性考虑
                //内部使用的就是setnx(后续可以开启一个定时任务，根据文章发布状态，定期将redis中的幂等键删除)
                Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "");

                if (flag) {
                    //将wmnews的信息同步到article中
                    apArticleService.saveAticle(wmNews);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            //删除redis中幂等性保障的key
            redisTemplate.delete(key);

            //出现了异常，不能确认，重复消费
            acknowledgment.nack(0);
        }

        //没有出现异常，正常确认消费
        acknowledgment.acknowledge();
    }
}
